package com.hfzy.ihk.common.web.context;

/**
 * Created by Administrator on 2018/12/26.
 *
 * @author wws
 */

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@Slf4j
public class SessionThreadContextFilter extends GenericFilterBean
{

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException
    {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;

//        final String origin = httpServletRequest.getHeader("origin");
//        if (origin!=null && origin.trim().length()>0) {
//            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
//        } else {
//            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
//        }
//        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
//        httpServletResponse.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
//        httpServletResponse.setHeader("Access-Control-Allow-Headers","content-type,access-control-allow-origin,access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,serviceName,locale");

        try{
            WebThreadContextHolder.setRequestResponse(httpServletRequest, httpServletResponse);
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            log.error("异常：", e);
        } finally {
            WebThreadContextHolder.clearRequestResponse();
        }
    }

    @Override
    public void destroy()
    {
    }
}
